package wnhz.com.business.shareshop.ui;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.renderscript.Type;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.nostra13.universalimageloader.utils.L;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wnhz.com.business.MyApplication;
import wnhz.com.business.R;
import wnhz.com.business.base.BaseActivity;
import wnhz.com.business.base.BaseRVAdapter;
import wnhz.com.business.base.BaseViewHolder;
import wnhz.com.business.shareshop.activity.home.ClassFromHomeActivity;
import wnhz.com.business.shareshop.bean.HotSearchBean;
import wnhz.com.business.shareshop.bean.SearchResultBean;
import wnhz.com.business.shareshop.bean.StoreSearchBean;
import wnhz.com.business.uitls.MyCallBack;
import wnhz.com.business.uitls.Url;
import wnhz.com.business.uitls.XUtil;
import wnhz.com.business.view.MyRecyclerView;

/**
 * 分类的搜索二级界面
 */
public class SeachActivityS extends BaseActivity {

    @BindView(R.id.v_statusbar)
    View vStatusbar;
    @BindView(R.id.edt_seach)
    EditText edtSeach;
    @BindView(R.id.iv_actionbar_right)
    ImageView ivActionbarRight;
    @BindView(R.id.tv_actionbar_right)
    TextView tvActionbarRight;
    @BindView(R.id.lay_actionbar_right)
    RelativeLayout layActionbarRight;
    @BindView(R.id.tv_1)
    TextView tv1;
    @BindView(R.id.view1)
    View view1;
    @BindView(R.id.rl_1)
    RelativeLayout rl1;
    @BindView(R.id.tv_2)
    TextView tv2;
    @BindView(R.id.view2)
    View view2;
    @BindView(R.id.rl_2)
    RelativeLayout rl2;
    @BindView(R.id.rl_hot)
    RecyclerView rlHot;
    @BindView(R.id.rl_history)
    MyRecyclerView rlHistory;
    @BindView(R.id.tv_clear)
    TextView tv_clear;

    private List<SearchResultBean.InfoBean> infoBeanList = new ArrayList<>();//存放搜索结果的集合
    private List<HotSearchBean.HotBean> infoHotList = new ArrayList<>();//热门搜索的数据
    private List<HotSearchBean.HistoryBean> infoHistoryList = new ArrayList<>();//历史搜索的数据
    private List<StoreSearchBean.InfoBean> infoStoreList = new ArrayList<>();//店铺集合
    private BaseRVAdapter mHistoryAdapter;
    private int topTag = 0;//0:默认是搜索全部商品的, 1:搜索商店的
    private int goods_type = 4;//1.拼团  2.返利  3.免费  4：共享商城


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_seachs);
        ButterKnife.bind(this);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
//            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            //改变状态栏颜色
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
            vStatusbar.setVisibility(View.VISIBLE);
            //获取到状态栏的高度
            int statusHeight = getStatusBarHeight();
            //动态的设置隐藏布局的高度
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) vStatusbar.getLayoutParams();
            params.height = statusHeight;
            vStatusbar.setLayoutParams(params);
        }
        
        initview();
    }

    private void initview() {


        rlHistory.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        rlHot.setLayoutManager(new GridLayoutManager(this,4,LinearLayoutManager.VERTICAL,false));

        edtSeach.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mHandler.postDelayed(runnableSearch, 1000);
            }
        });

        if (topTag == 0) {// 1.商品  2.店铺
            //热门搜索,历史数据
            hotSearchDatas(goods_type,1);
        }else if (topTag == 1){
            hotSearchDatas(goods_type,2);
        }
    }

    //热门搜索
    private void sethotdata() {

        BaseRVAdapter mHotBaseAdapter = new BaseRVAdapter(this,infoHotList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_hot;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                TextView tv_hot = holder.getTextView(R.id.tv_hot);
                if (null != infoHotList) {
                    tv_hot.setText(infoHotList.get(position).getContent());
                }
            }

        };

        mHotBaseAdapter.addItemClickListener(new BaseRVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                // TODO: 2018-01-28 0028 点击跳转到商品所属的列表

            }
        });

        rlHot.setAdapter(mHotBaseAdapter);
        mHotBaseAdapter.notifyDataSetChanged();
    }


    //(搜索的结果)
    private void sethistorydata() {

        mHistoryAdapter = new BaseRVAdapter(this,infoBeanList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_history;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                if (null != infoBeanList){
                    TextView goods_name = holder.getTextView(R.id.goods_name);
                    goods_name.setText(infoBeanList.get(position).getGoods_name());
                }
            }
        };

        mHistoryAdapter.addItemClickListener(new BaseRVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                // TODO: 2018-01-28 0028 点击跳转该商品所属的列表
                if (null != infoBeanList) {
                    Intent intent = new Intent(SeachActivityS.this, ClassFromHomeActivity.class);
                    if (topTag == 1) {
                        intent.putExtra("title",infoBeanList.get(position).getGoods_name() != null?infoBeanList.get(position).getGoods_name().substring(0,2):"商品");
                    }else {
                        intent.putExtra("title",infoBeanList.get(position).getGoods_name() != null?infoBeanList.get(position).getGoods_name().substring(0,2):"店铺");
                    }
                    startActivity(intent);
                }else {
                    MyToast("暂无匹配数据");
                }
            }
        });

        rlHistory.setAdapter(mHistoryAdapter);
        mHistoryAdapter.notifyDataSetChanged();
    }

    //历史数据(商品的)
    private void sethistorydataO() {

        mHistoryAdapter = new BaseRVAdapter(this,infoHistoryList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_history;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                if (null != infoHistoryList){
                    TextView goods_name = holder.getTextView(R.id.goods_name);
                    goods_name.setText(infoHistoryList.get(position).getContent());
                }
            }
        };

        mHistoryAdapter.addItemClickListener(new BaseRVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                // TODO: 2018-01-28 0028 点击跳转该商品所属的列表

            }
        });

        rlHistory.setAdapter(mHistoryAdapter);
        mHistoryAdapter.notifyDataSetChanged();
    }

    //历史数据(店铺的)
    private void sethistoryStoreData() {

        mHistoryAdapter = new BaseRVAdapter(this,infoStoreList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_history;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                if (null != infoStoreList){
                    TextView goods_name = holder.getTextView(R.id.goods_name);
                    goods_name.setText(infoStoreList.get(position).getName());
                }
            }
        };
        rlHistory.setAdapter(mHistoryAdapter);
        mHistoryAdapter.notifyDataSetChanged();
    }

    //清空搜索
    private void cleanSearchFun(int goods_type,int type){//INDEX_EMPTY_SEARCH
        Map<String,Object> maps = new HashMap<>();
        maps.put("token",MyApplication.getToken());
        maps.put("goods_type",goods_type);//1.拼团  2.返利  3.免费 4：共享商城
        maps.put("type",type);
        XUtil.Post(Url.INDEX_EMPTY_SEARCH,maps,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.optString("re"))){
                        MyToast(jsonObject.optString("info"));
                        if (null != infoHistoryList){
                            infoHistoryList.clear();
                            sethistorydata();
                        }
                        if (null != infoBeanList){
                            infoBeanList.clear();
                            sethistorydataO();
                        }
                    }else if ("-1".equals(jsonObject.optString("re"))){
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                        MyToast(jsonObject.optString("info"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    /**
     * 店铺搜索
     */
    private void searchStores(String goods_type,String search){
        Map<String,Object> maps = new HashMap<>();
        maps.put("token", MyApplication.getToken());
        maps.put("goods_type",goods_type);
        maps.put("search",search);
        XUtil.Post(Url.SRTORE_SEARCH,maps,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.optString("re"))){
                        Gson gson = new Gson();
                        StoreSearchBean storeSearchBean = gson.fromJson(result,StoreSearchBean.class);
                        if (null != infoStoreList){
                            infoStoreList.clear();
                        }
                        infoStoreList.addAll(storeSearchBean.getInfo());
                        sethistoryStoreData();
                    }else if("-1".equals(jsonObject.optString("re"))){
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                       MyToast(jsonObject.optString("info"));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    /**
     * 商品搜索
     */
    private void goodsSearchAll(String goods_type,String search,String sort,String type,String store_id){

        Map<String,Object> maps = new HashMap<>();
        maps.put("token", MyApplication.getToken());
        maps.put("goods_type",goods_type);
        maps.put("search",search);
        maps.put("sort",sort);
        maps.put("type",type);
        maps.put("store_id",store_id);
        XUtil.Post(Url.GOODS_SEARCH_ALL,maps,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.optString("re"))){
                        Gson gson = new Gson();
                        SearchResultBean resultBean = gson.fromJson(result,SearchResultBean.class);
                        if (null != infoBeanList){
                            infoBeanList.clear();
                        }
                        infoBeanList.addAll(resultBean.getInfo());

                        sethistorydata();
                    }else if ("-1".equals(jsonObject.optString("re"))){
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                        MyToast(jsonObject.optString("info"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    //搜索全部商品
    Runnable runnableSearch = new Runnable() {
        @Override
        public void run() {

            if (!TextUtils.isEmpty(edtSeach.getText().toString().trim())) {
                if (topTag == 0) {
                    goodsSearchAll("4",edtSeach.getText().toString().trim(),"1","1","");
                }else if (topTag == 1){
                    searchStores("4",edtSeach.getText().toString().trim());
                }
            }
        }
    };



    //热门搜索
    private void hotSearchDatas(int goods_type, int type){
        Map<String,Object> maps = new HashMap<>();
        maps.put("token",MyApplication.getToken());
        maps.put("goods_type",goods_type);
        maps.put("type",type);
        XUtil.Post(Url.INDEX_SEARCHLIST,maps,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.optString("re"))){
                        Gson gson = new Gson();
                        HotSearchBean hotSearchBean = gson.fromJson(result,HotSearchBean.class);
                        if (null != infoHotList){
                            infoHotList.clear();
                        }
                        if (null != infoHistoryList){
                            infoHistoryList.clear();
                        }
                        infoHistoryList.addAll(hotSearchBean.getHistory());
                        sethistorydataO();
                        infoHotList.addAll(hotSearchBean.getHot());
                        sethotdata();
                    }else if ("-1".equals(jsonObject.getString("re"))){
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                        MyToast(jsonObject.optString("info"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });

    }

    @OnClick({R.id.rl_1, R.id.rl_2,R.id.lay_actionbar_right,R.id.tv_clear})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_1:
                tv1.setTextColor(getResources().getColor(R.color.red255));
                tv2.setTextColor(getResources().getColor(R.color.set_right_text));
                view1.setVisibility(View.VISIBLE);
                view2.setVisibility(View.GONE);
                topTag = 0;
                hotSearchDatas(goods_type,1);
                break;
            case R.id.rl_2:
                tv1.setTextColor(getResources().getColor(R.color.set_right_text));
                tv2.setTextColor(getResources().getColor(R.color.red255));
                view1.setVisibility(View.GONE);
                view2.setVisibility(View.VISIBLE);
                topTag = 1;
                hotSearchDatas(goods_type,2);
                break;

            case R.id.lay_actionbar_right:
                finish();
                break;
            case R.id.tv_clear:
                if (null == infoBeanList){
                    return;
                }
                if (null == infoHistoryList){
                   return;
                }
                if (null == infoStoreList){
                    return;
                }

                if (topTag == 0) {// type  1.商品  2.店铺
                    cleanSearchFun(4,1);
                }if (topTag == 1){
                    cleanSearchFun(4,2);
                sethistoryStoreData();
                sethistorydataO();
                sethistorydata();
                }

                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mHandler){
            mHandler.removeCallbacks(runnableSearch);
        }
    }
}
